package com.basker.pisces.core.meta.bean;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.util.Assert;

import com.basker.pisces.core.meta.CollectionField;
import com.basker.pisces.core.meta.IDataObjectMeta;

public class BeanCollectionField extends CollectionField {
    private BeanFieldDescriptor beanFieldDescriptor;

    public BeanCollectionField(BeanFieldDescriptor beanFieldDescriptor, String name, String displayName,
                               IDataObjectMeta itemObjectMeta) {
        super(name, displayName, itemObjectMeta);
        this.beanFieldDescriptor = beanFieldDescriptor;

        Assert.isTrue(List.class.isAssignableFrom(beanFieldDescriptor.getProperyType()),
                "collection field's type must be List!");
    }

    public Method getGetMethod() {
        return beanFieldDescriptor.getGetMethod();
    }

    public Method getSetMethod() {
        return beanFieldDescriptor.getSetMethod();
    }

    @Override
    public Collection<Object> getValue(Object dataObject) {
        Object val = this.beanFieldDescriptor.getValue(dataObject);

        if (val == null) {
            if (this.getItemObjectMeta().isReadOnly()) {
                val = new ArrayList<>();
            } else {
                val = new DataContractList<>();
            }

            this.setValue(dataObject, val);
        }

        @SuppressWarnings("unchecked")
        Collection<Object> col = (Collection<Object>) val;
        return col;

    }

    @Override
    public void setValue(Object dataObject, Object value) {
        this.beanFieldDescriptor.setValue(dataObject, value);
    }

}
